package com.bigdata.wsr.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 工具类
 *
 * @author rui.wang
 * @date 2022/11/08
 */
@Slf4j
public class TheTableListSyncUtil {
    public static String getDbTableList(String database, String tables, List<String> tableList) {
        StringBuilder dbTableList = new StringBuilder();
        int count = 0;
        if (tables.contains(",")) {
            String[] split = tables.split(",");
            for (String table : split) {
                tableList.add(table);
                count++;
                if (count > 1) {
                    dbTableList.append(",").append(database).append(".").append(table);
                } else {
                    dbTableList.append(database).append(".").append(table);
                }
            }
        } else {
            tableList.add(tables);
            dbTableList.append(database).append(".").append(tables);
        }
        return dbTableList.toString();
    }

    public static void deleteByNonTimeFields(String table, JSONObject jsonObj,DruidDataSource dorisDs) {
        Connection conn = null;
        PreparedStatement stmt = null;

        StringBuilder delSql = new StringBuilder();
        delSql.append("delete from ")
                .append(table)
                .append(" where ");

        int count = 0;
        for (String nonTimeField : jsonObj.keySet()) {
            count++;
            if (count == 1) {
                delSql.append(nonTimeField)
                        .append(" = ")
                        .append("'")
                        .append(jsonObj.getString(nonTimeField))
                        .append("'");
            } else if (count > 1) {
                delSql.append(" and ")
                        .append(nonTimeField)
                        .append(" = ")
                        .append("'")
                        .append(jsonObj.getString(nonTimeField))
                        .append("'");
            }
        }

        String deleteSql = delSql.toString();
        log.info("deleteSql ---> {}", deleteSql);

        try {
            conn = dorisDs.getConnection();
            stmt = conn.prepareStatement(deleteSql);
            stmt.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException se2) {
                se2.printStackTrace();
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}
